package com.fiberhome.ztelauncher.core;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Window;

import com.fiberhome.zte_launcher.R;
import com.fiberhome.ztelauncher.resource.ResourceManager;
import com.fiberhome.ztelauncher.util.BitmapUitl;
import com.fiberhome.ztelauncher.xml.bean.FileBean;
import com.fiberhome.ztelauncher.xml.bean.LaunchDataCommon;
import com.fiberhome.ztelauncher.xml.bean.Launcher;
import com.fiberhome.ztelauncher.xml.bean.LauncherLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by Deed on 2018/3/19.
 */

public class MainActivity extends FragmentActivity {

    private HomeLayout homeLayout;
    private Handler mHandler01 = new Handler();
    private Handler mHandler02 = new Handler();

    /* 上一次User有动作的Time Stamp */
    private Date lastUpdateTime;
    /* 计算User有几秒没有动作的 */
    private long timePeriod;

    /* 静止超过N秒将自动进入屏保 */
    private float mHoldStillTime = 200;
    private long intervalKeypadeSaver = 1000;
    private ArrayList<String> listUrl = new ArrayList<String>();
    //page切换时间
    private int rollTime = 100;
    private int waitTime = 100;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        homeLayout = (HomeLayout) findViewById(R.id.homeLayout);
        Launcher launcher = ResourceManager.getResourceManager().currentLauncher();
        getLauncherLayout(launcher);
//        ResourceManager.getResourceManager().getLauncher(new Observer<Launcher>() {
//            @Override
//            public void onSubscribe(@NonNull Disposable disposable) {
//
//            }
//
//            @Override
//            public void onNext(@NonNull Launcher launcher) {
////                rollTime = launcher.rollTime.value;
////                waitTime = rollTime;
//            	getLauncherLayout(launcher);
//            }
//
//            @Override
//            public void onError(@NonNull Throwable throwable) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });

        /* 初始取得User可触碰屏幕的时间 */
        lastUpdateTime = new Date(System.currentTimeMillis());
//        getData();
    }

    private void getData() {
        listUrl.add("720p_en/assets/images/thematic/background/552a0958-f944-428e-a4c1-3255df55ee0b.jpg");
        listUrl.add("720p_en/assets/images/Ads_Banner/8aa1804a-d77a-4d28-9d31-da7a1945b3e0.jpg");
        listUrl.add("720p_en/assets/images/Ads_Banner/194813cb-f64f-4181-b326-a513db415256.jpg");
        listUrl.add("720p_en/assets/images/Ads_Banner/8a3a89fa-812a-4b14-b8a5-0e0dc909f60c.jpg");
        listUrl.add("720p_en/assets/images/Ads_Banner/d590bf3c-c4a6-419e-8677-093095e51b48.jpg");
    }


    /**
     * 获取页面布局
     *
     * @param launcher
     */
    private void getLauncherLayout(final Launcher launcher) {
        ResourceManager.getResourceManager().getLauncherLayout(launcher.layout, new Observer<LauncherLayout>() {
            @Override
            public void onSubscribe(@NonNull Disposable disposable) {

            }

            @Override
            public void onNext(@NonNull LauncherLayout launcherLayout) {
                LauncherLayout.PageCommon pageCommon = launcherLayout.pageCommon;
                List<LauncherLayout.Page> pageList = launcherLayout.pageList.pageList;
                sortPage(pageList);
                getLaunchDataCommon(launcher, pageList, launcher.pages.pages, pageCommon);
                BitmapUitl.loadBackground(MainActivity.this, homeLayout, pageCommon.defaultBackground);
            }

            @Override
            public void onError(@NonNull Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取导航栏以及公共数据
     *
     * @param launcher
     */
    private void getLaunchDataCommon(Launcher launcher, final List<LauncherLayout.Page> pageList,
                                     final List<FileBean> pagebeanList, final LauncherLayout.PageCommon pageCommon) {
        ResourceManager.getResourceManager().getCommonData(launcher.commonData, new Observer<LaunchDataCommon>() {
            @Override
            public void onSubscribe(@NonNull Disposable disposable) {

            }

            @Override
            public void onNext(@NonNull LaunchDataCommon launchDataCommon) {
                homeLayout.setHomeData(launchDataCommon, pageList, pagebeanList, pageCommon);
            }

            @Override
            public void onError(@NonNull Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 页面排序
     *
     * @param pageList
     */
    private void sortPage(List<LauncherLayout.Page> pageList) {
        Collections.sort(pageList, new Comparator<LauncherLayout.Page>() {
            @Override
            public int compare(LauncherLayout.Page page, LauncherLayout.Page t1) {
                return page.order - t1.order;
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return homeLayout.onKeyDown(keyCode, event);
    }

    /**
     * 计时线程
     */
    private Runnable mTask01 = new Runnable() {

        @Override
        public void run() {
            Date timeNow = new Date(System.currentTimeMillis());
            // 计算User静止不动作的时间间距
            //当前的系统时间 - 上次触摸屏幕的时间 = 静止不动的时间
            timePeriod = (long) timeNow.getTime() - (long) lastUpdateTime.getTime();

            //将静止时间毫秒换算成秒
            float timePeriodSecond = ((float) timePeriod / 1000);

            if (timePeriodSecond > rollTime) {
                homeLayout.switchPage();
                rollTime += waitTime;
            }
            //判断禁止时间大于规定的时间，进入屏保并重置时间
            if (timePeriodSecond > mHoldStillTime) {
                updateUserActionTime();
                showScreenSaver();
            } else {

                mHandler01.postDelayed(mTask01, intervalKeypadeSaver);
            }
        }
    };

    /**
     * 显示屏保
     */
    private void showScreenSaver() {
        if (listUrl.size() > 0) {
//            ScreenSaveActivity.goInto(this, listUrl);
        } else {
            mHandler01.removeCallbacks(mTask01);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        updateUserActionTime();
        return super.dispatchKeyEvent(event);
    }

    /**
     * 重置静止时间和上次操作的时间
     */
    public void updateUserActionTime() {
        Date timeNow = new Date(System.currentTimeMillis());
        timePeriod = timeNow.getTime() - lastUpdateTime.getTime();
        lastUpdateTime.setTime(timeNow.getTime());
        rollTime = 100;
    }

    @Override
    protected void onResume() {
        //activity显示的时候启动线程
    	updateUserActionTime();
        mHandler01.postAtTime(mTask01, intervalKeypadeSaver);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //activity不可见的时候取消线程
        mHandler01.removeCallbacks(mTask01);
        super.onPause();
    }
}
